<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-17
 * Time: 下午4:10
 */
namespace Institution\Controller;
use User\Api\UserApi;

class PublicController extends \Think\Controller {
    /*
     * 用户登录
     */
    public function login($username = null, $password = null, $verify = null){
        if (IS_POST) {
            $uid = D('User')->login($username, $password);
            if (0 < $uid) {
                if (D('User')->a_login($uid)) {
                    $this->success('登录成功',U('Task/myTask'));
                } else {
                    $this->error('登录失败');
                }
            } else {
                switch ($uid) {
                    case -1:
                        $error = '用户不存在';
                        break;
                    case -2:
                        $error = '用户密码不正确';
                        break;
                    case -3:
                        $error = '用户被禁用';
                        break;
                    case -4:
                        $error = '该用户组不允许登录';
                        break;
                    default :
                        $error = '未知错误';
                        break;
                }
                $this->error($error);
            }
        } else {
            $value2 = cookie('remember_password_jg');

            $value3 = cookie('remember_account_jg');

            if ($value2 && $value3) {
                $this->assign('pass_jg', $value2);

                $this->assign('account_jg', $value3);
            }
//
//            $username=isset($_COOKIE["username"])?$_COOKIE["username"]:"";
//            $password=isset($_COOKIE["password"])?$_COOKIE["password"]:"";
//            $this->assign('username',$username);
//            $this->assign('password',$password);

            $this->display();
        }
    }
	
	/**
	* 统一身份登录
	*/
	public function idlogin(){
		Vendor('CAS.source.CAS'); 
        $phpCAS = new \phpCAS();
		$phpCAS::client(CAS_VERSION_2_0,'cas.jalis.nju.edu.cn',443,'cas');
		$phpCAS::setNoCasServerValidation();
		$phpCAS::forceAuthentication();
		
		if (isset($_REQUEST['logout'])) {
		 $param=array("service"=>"http://kjcx.jalis.nju.edu.cn/index.php/Institution/Public/idlogin.html");//退出登录后返回
		 $phpCAS::logout($param);
		}
		// for this test, simply print that the authentication was successfull
		$uinfo = $phpCAS::getUser();
		if($uinfo){
			$appUser_arr = $phpCAS::getAttributes();
			// echo json_encode($appUser_arr);exit;
			$where = array('username'=>$appUser_arr['userName']);
            $info = M('User')->where($where)->getField('id,username,typeid');
            $dep = M('department')->where(array('name'=>$appUser_arr['instName']))->getField('id');
			// echo json_encode($info);exit;
			$role_arr = array(
				'kjcx.general'		=> 2,
				'kjcx.center'		=> 11,
				// 'kjcx.institution'	=> 1,
				'administrator'		=> 1,
				'kjcx.dispenser'	=> 121,
				'kjcx.searcher'		=> 102,
				'kjcx.auditor'		=> 104,
				'kjcx.collector'	=> 121,
			);
			if($info == null){
				$data = array(
					'username'	=>	$appUser_arr['userName'],
					'password'	=>	md5(123456),
					'typeid'	=>	$role_arr[$appUser_arr['appRole']],
					'status'	=>	1,
					'department'=>	$dep,
					'name'		=>	$appUser_arr['name'],
					'sex'		=>	$appUser_arr['sex'],
				);
				$uid = M('User')->data($data)->add();
				M('auth_group_access')->data(array('uid'=>$uid,'group_id'=>$role_arr[$appUser_arr['appRole']]))->add();
			}else{
				$info = array_values($info);
				$uid = $info[0]['id'];
			}

			if($role_arr[$appUser_arr['appRole']] == 1){
			// if($info[0]['typeid'] == 2){
				if (D('User')->a_login($uid)) {
					$this->success('登录成功',U('Task/myTask'));
				} else {
					$this->error('登录失败');
				}
			}else{
				header("Location: http://kjcx.jalis.nju.edu.cn/index.php/Home/Public/idlogin.html?uid=".$uid);
			}
		}
	}

    /*
     * 用户退出
     */
    public function logout(){
        if(is_login()){
            D('User')->logout();
            session('[destroy]');
			
        }
		//退出统一身份登录
		Vendor('CAS.source.CAS'); 
		$phpCAS = new \phpCAS();
		$phpCAS::client(CAS_VERSION_2_0,'cas.jalis.nju.edu.cn',443,'cas');
		$phpCAS::setNoCasServerValidation();
		$phpCAS::forceAuthentication();
		$param=array("service"=>"http://kjcx.jalis.nju.edu.cn/index.php/Home/Desk/index.html");//退出登录后返回
		$phpCAS::logout($param);
		
		$this->redirect('login');
    }

    /*
     * 验证码
     */
    public function verify(){
        $verify = new \Think\Verify();
        $verify->entry(2);
    }
    /**
     * 修改密码
     * @return void
     */

    public function changePwd(){

            $password = trim($_POST['code']);
            $user = M('User');
            $check = $user->find($_SESSION['user_auth']['uid']);
            if ($check['password'] != md5($password)) {
                $this->error('原始密码输入不正确');
            }

            $data['password'] = $_POST['password'];
            if (!$this->sec_check1($data['password'])) {
                $this->error('原始密码和新密码不能一样');
            }
            if(strlen($data['password'])<6 || strlen($password)>20)
            {
                $this->error('密码只允许在6-20位');
            }
            $repassword = $_POST['repassword'];
            if ($data['password'] !== $repassword) {
                $this->error('两次输入的密码不一样');
            }
            $data['password'] = md5($data['password']);
            $user = M('User');
            $res = $user->where('id='.$_SESSION['user_auth']['uid'])->save($data);
            if ($res) {
                $id = session('user_auth.uid');
                action_log('user_changePassword', 'user', $id, $id);
                $this->success('密码已经修改成功',__APP__.'/Institution/Public/logout');
//                $this->redirect(U('logout'));
            } else {
                $this->error('密码修改失败');
            }

    }
    //检查密码输入的是否正确
    protected function checkpwd1($pwd){
        $map['id'] = UID;
        $user = M('User');
        $check = $user->find(UID);
        if($check['password'] === md5($pwd)){
            return true;
        }else{
            return false;
        }
    }
    //验证密码是否与旧密码相同
    protected function sec_check1($newPassword){
        $user = M('User');
        $check = $user->find(UID);
        if($check['password'] === md5($newPassword)){
            return false;
        }else{
            return true;
        }
    }
}